var express = require('express');
var router = express.Router();
var sql = require('./../sql')
var Order = require('./../sql/orders')
var Cart = require('./../sql/cart')
var uuid = require('node-uuid')

// 生成订单
router.get('/add', (req, res, next) => {
  // 1、获取前端提交的订单数据 "[{},{},{}]" -- 转成对象
  let list = JSON.parse(req.query.str)
  let userid = req.query.userid // 获取用户id
  let orderid = 'order_' + uuid.v1() // 生成订单的id
  let arr = [] // 订单列表数据
  const d = new Date()
  let date = d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate() + ' ' + d.getHours() + ':' + d.getMinutes()
  // 2、遍历数据，获取订单的信息
  list.map(item => {
    arr.push({
      proid: item.proid,
      proimg: item.proimg,
      proname: item.proname,
      price: item.price * 1,
      num: item.num * 1,
      time: item.time
    })
  })
  // 3、插入数据库
  sql.insert(Order, {
    orderid: orderid,
    userid: userid,
    status: 0, // 订单状态 0 待付款 1 待收货（已支付） 2 待评价
    list: arr,
    date: date
  }).then(() => {
    // 4、生成订单后要删除购物车的数据
    let p = list.map(item => {
      return sql.delete(Cart, { cartid: item.cartid })
    })
    return Promise.all(p)
    }).then(() => {
      res.send({
        code: '200',
        message: '生成订单',
        data: { // 用于在确认订单页面 查询订单的信息
          orderid: orderid
        }
    })
  })
})
// 查看订单
router.get('/', (req, res, next) => {
  // res.send('订单')
  // 1、获取订单的状态
  let status = req.query.status
  let orderid = req.query.orderid
  // 2、查询订单的信息 只通过用户id 得到该用户全部订单
  let findData = { userid: req.query.userid }
  if (status) { // 3、如果传了状态，查询改状态数据
    findData.status = status
  }
  if (orderid) {
    findData.orderid = orderid
  }
  sql.find(Order, findData, { _id: 0 }).then(data => {
    if (data.length === 0){
      res.send({
        code: '100',
        message: '暂无数据'
      })
    } else {
      res.send({
        code: '200',
        message: '订单列表',
        len: data.length,
        data: data
      })
    }
  })
})
router.get('/update', (req, res, next) => {
  // let status = req.query.status
  let orderid = req.query.orderid
  sql.update(Order, { orderid: orderid }, { $set: { status: 1 } }).then(data => {
    res.send({
      code: '200',
      message: '该订单已完成支付'
    })
  })
})
module.exports = router;
